package com.itrip.filter;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.itrip.dto.ResponseDTO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class LoginFilter implements Filter {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        //从请求头中，获取token令牌
        String token = request.getHeader("token");
        ResponseDTO responseDTO = null;
        if(!StringUtils.isEmpty(token)){
            //请求头有token,到Redis中验证是否存在
            Boolean hasKey = redisTemplate.hasKey(token);

            if(hasKey != null && hasKey){
                //token在Redis中存在，放行
                filterChain.doFilter(servletRequest,servletResponse);
                return;//停止后续的代码的运行
            }else{
                responseDTO = new ResponseDTO(102,"token已失效",null);
            }
        }else{
            //token未传递
            responseDTO = new ResponseDTO(102,"token未传递",null);
        }

        //获取输出流
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSONObject.toJSONString(responseDTO));
    }

    @Override
    public void destroy() {

    }
}
